package com.mywork.mvpkodeinxml.net

import com.mywork.mvpkodeinxml.common.SERVER_ADDRESS
import com.orhanobut.logger.Logger
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import okio.Buffer
import okio.BufferedSink
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.simplexml.SimpleXmlConverterFactory
import java.nio.charset.Charset


object RetrofitFactory {
    private val retrofit: Retrofit
    //private val interceptor: Interceptor
    private val loggingInterceptor: Interceptor

    init {
        /**
         * 统一添加Header
         */
        /*interceptor = Interceptor { chain ->
            val request = chain.request()
                .newBuilder()
                .addHeader("Content-Type", "text/xml;charset=UTF-8")
                .addHeader("charset", "utf-8")
                //.addHeader("token",AppPrefsUtils.getString(KEY_SP_TOKEN))
                .build()

            chain.proceed(request)
        }*/

        /**
         * 日志拦截器
         */
        loggingInterceptor = Interceptor { chain ->
            val request = chain.request()

            //requestBody
            val sink: BufferedSink = Buffer()
            request.body?.writeTo(sink)
            val requestBodyStr = sink.buffer.readString(Charset.forName("utf-8"))
            //URL
            val requestUrl = request.url.toString()
            //requestMethod
            val requestMethod = request.method.toString()
            if (requestUrl.contains("optag=1", true)) {
                Logger.d("$requestMethod : $requestUrl")
            } else {//上传文件不打印body
                Logger.d("$requestMethod : $requestUrl\n$requestBodyStr")
            }
            val response = chain.proceed(request)
            val contentType = response.body?.contentType()?.type
            //contentType:text/xml; charset=utf-8
            //contentType:application/pdf
            if (contentType == "text") {
                //这里不能直接使用response.body().string()的方式输出日志，response中的流会被关闭，需要创建出一个新的response给应用层处理
                val source = response.body?.source()
                source?.request(Long.MAX_VALUE) // Buffer the entire body.
                val responseBodyStr = source?.buffer?.clone()?.readString(Charset.forName("utf-8"))
                Logger.d("Response: code=${response.code}\n$responseBodyStr")
            }
            response
        }

        retrofit = Retrofit.Builder()
            .baseUrl(SERVER_ADDRESS)
            .addConverterFactory(SimpleXmlConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(initClient())
            .build()

    }

    private fun initClient(): OkHttpClient {
        return OkHttpClient.Builder()
            //.addInterceptor(interceptor)
            .addInterceptor(loggingInterceptor)
            //.addInterceptor(initLogInterceptor())
            .build()

    }

    private fun initLogInterceptor(): Interceptor {
        val interceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
            override fun log(message: String) {
                Logger.d(message)
            }

        })
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        return interceptor
    }

    fun <T> create(service: Class<T>): T {
        return retrofit.create(service)
    }

}